package com.geek.netty.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @program netty-server
 * @description: netty
 * @author: chanzhugang
 * @create: 2021/08/16 19:13
 */
public class NettyDemo {

    /**
     * Netty 代码模版 ： 线程模型：每一个网络连接关联到一个线程
     * @param args
     */
    public static void main(String[] args) {
        // 事件处理器
        EchoServerHandler handler = new EchoServerHandler();

        // EventLoop
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加事件处理器
                            ch.pipeline().addLast(handler);
                        }
                    });
            // 绑定端口
            ChannelFuture future = bootstrap.bind(9090).sync();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}